package com.spacex.danhuang.polive.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.spacex.danhuang.polive.Application.VApplication;
import com.spacex.danhuang.polive.Constants.Constants;
import com.spacex.danhuang.polive.R;
import com.spacex.danhuang.polive.fragments.MainPageFragment;
import com.spacex.danhuang.polive.fragments.UserPageFragment;

import org.json.JSONException;
import org.json.JSONObject;

import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class AppMainActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "AppMainActivity";

    private Socket mSocket;
    private VApplication app;

    private MainPageFragment mainPageFragment;
    private UserPageFragment userPageFragment;

    private TextView tv_app_main_tab_mainpage;
    private TextView tv_app_main_tab_po;
    private TextView tv_app_main_tab_userpage;

    private FragmentManager fragmentManager;

    private String mUserId;
    private int mBondState;
    private String mMobileBonded;
    private String mNickname;
    private int mSex;

    private int currentIndex = Constants.APP_MAIN_TAB_MAINPAGE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_main);

        app = (VApplication)getApplication();
        mSocket = app.getSocket();
        mUserId = app.getUserId();

        fragmentManager = getSupportFragmentManager();

        Intent intent = new Intent(AppMainActivity.this, LoginActivity.class);
        AppMainActivity.this.startActivityForResult(intent, 0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Activity.RESULT_OK != resultCode) {
            finish();
            return;
        }

        initView();

        attemptGetUserInfo(mUserId);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mSocket.connected()) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                attemptLogout();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();

        mSocket.on("message", onHandleMsg);
    }

    @Override
    protected void onPause() {
        super.onPause();

        mSocket.off("message", onHandleMsg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mSocket.disconnect();
    }

    private void initView() {
        tv_app_main_tab_mainpage = (TextView)findViewById(R.id.tv_app_main_tab_mainpage);
        tv_app_main_tab_po = (TextView)findViewById(R.id.tv_app_main_tab_po);
        tv_app_main_tab_userpage = (TextView)findViewById(R.id.tv_app_main_tab_userpage);

        tv_app_main_tab_mainpage.setOnClickListener(this);
        tv_app_main_tab_po.setOnClickListener(this);
        tv_app_main_tab_userpage.setOnClickListener(this);

        selectFragment(Constants.APP_MAIN_TAB_MAINPAGE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.tv_app_main_tab_mainpage:
                if (currentIndex == Constants.APP_MAIN_TAB_MAINPAGE) {
                    return;
                }
                selectFragment(Constants.APP_MAIN_TAB_MAINPAGE);
                break;
            case R.id.tv_app_main_tab_po:
                startPublish();
                break;
            case R.id.tv_app_main_tab_userpage:
                if (currentIndex == Constants.APP_MAIN_TAB_USERPAGE) {
                    return;
                }
                selectFragment(Constants.APP_MAIN_TAB_USERPAGE);
                break;
            default:
                break;
        }
    }

    @SuppressLint("NewApi")
    private void selectFragment(int index) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        resetFragments(transaction);
        switch (index)
        {
            case Constants.APP_MAIN_TAB_MAINPAGE:
                if (mainPageFragment == null) {
                    mainPageFragment = new MainPageFragment();
                    transaction.add(R.id.fl_app_main_body, mainPageFragment);
                } else {
                    transaction.show(mainPageFragment);
                }
                //tv_app_main_tab_mainpage.setTextAppearance(R.style.MainTabSelected);
                tv_app_main_tab_mainpage.setTextColor(Color.RED);
                currentIndex = Constants.APP_MAIN_TAB_MAINPAGE;
                break;
            case Constants.APP_MAIN_TAB_USERPAGE:
                if (userPageFragment == null) {
                    userPageFragment = new UserPageFragment();
                    transaction.add(R.id.fl_app_main_body, userPageFragment);
                } else {
                    transaction.show(userPageFragment);
                }
                //tv_app_main_tab_userpage.setTextAppearance(R.style.MainTabSelected);
                tv_app_main_tab_userpage.setTextColor(Color.RED);
                currentIndex = Constants.APP_MAIN_TAB_USERPAGE;
                break;
            default:
                break;
        }
        transaction.commit();
    }

    private void resetFragments(FragmentTransaction transaction) {
        if (mainPageFragment != null) {
            transaction.hide(mainPageFragment);
        }
        if (userPageFragment != null) {
            transaction.hide(userPageFragment);
        }

        //tv_app_main_tab_mainpage.setTextAppearance(R.style.MainTabUnSelected);
        //tv_app_main_tab_userpage.setTextAppearance(R.style.MainTabUnSelected);
        tv_app_main_tab_mainpage.setTextColor(Color.BLACK);
        tv_app_main_tab_userpage.setTextColor(Color.BLACK);
    }

    private void startPublish() {
        attemptBeginShow();
    }

    /**
     * request for get information of a user with data(userid)
     * @param userid
     */
    private void attemptGetUserInfo(String userid) {

        JSONObject attempGetInfoJSON = new JSONObject();
        JSONObject attempGetInfoData = new JSONObject();
        try {
            attempGetInfoJSON.put("request", Constants.GET_USERINFO_NAME);

            attempGetInfoData.put("userid", userid);
            attempGetInfoJSON.put("data", attempGetInfoData);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String tmpGetInfoStr = attempGetInfoJSON.toString();
        Log.i(TAG, "get user info send");
        Log.i(TAG, tmpGetInfoStr);
        mSocket.send(tmpGetInfoStr);
    }

    /**
     * request for begin a show
     * data: null
     */
    private void attemptBeginShow() {

        JSONObject attempBeginShowJSON = new JSONObject();
        try {
            attempBeginShowJSON.put("request", Constants.BEGIN_SHOW_NAME);
            attempBeginShowJSON.put("data", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String tmpBeginShowStr = attempBeginShowJSON.toString();
        Log.i(TAG, "begin live show send");
        Log.i(TAG, tmpBeginShowStr);
        mSocket.send(tmpBeginShowStr);
    }

    /**
     * request for begin a show
     * data: null
     */
    private void attemptLogout() {

        JSONObject attemptLogoutJSON = new JSONObject();
        try {
            attemptLogoutJSON.put("request", Constants.LOGOUT_NAME);
            attemptLogoutJSON.put("data", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String tmpLogoutStr = attemptLogoutJSON.toString();
        Log.i(TAG, "logout send");
        Log.i(TAG, tmpLogoutStr);
        mSocket.send(tmpLogoutStr);
    }

    /**
     * Socket事件监听处理函数（收到"message"事件时触发）
     **/
    protected Emitter.Listener onHandleMsg = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.i(TAG, "onHandleMsg received data");

            String onHandleMsgStr = (String)args[0];
            Log.i(TAG, onHandleMsgStr);
            JSONObject onHandleMsgJSON = null;
            try {
                onHandleMsgJSON = new JSONObject(onHandleMsgStr);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            String rsp_name = "";
            int rsp_status = 0;
            String rsp_errmsg = "";

            JSONObject onHandleMsgData = null;

            try {
                if (onHandleMsgJSON != null) {
                    rsp_name = onHandleMsgJSON.getString("response");
                    rsp_status = onHandleMsgJSON.getInt("status");
                    rsp_errmsg = onHandleMsgJSON.getString("errormsg");
                    Log.i(TAG, String.format("activity rsp_name = %s", rsp_name));
                    Log.i(TAG, String.format("rsp_status = %d", rsp_status));
                    Log.i(TAG, String.format("rsp_errmsg = %s", rsp_errmsg));

                    onHandleMsgData = onHandleMsgJSON.getJSONObject("data");
                }

            } catch (JSONException e) {
                e.printStackTrace();
                return;
            }

            handleSwitchMethod(rsp_name, rsp_status, rsp_errmsg, onHandleMsgData);
        }
    };

    protected void handleSwitchMethod(String rsp_name, int rsp_status, String rsp_errmsg, JSONObject onHandleMsgData) {
        switch (rsp_name) {
            case Constants.GET_USERINFO_NAME:
                Log.i(TAG, "handleGetUserInfo");
                handleGetUserInfo(rsp_status, rsp_errmsg, onHandleMsgData);
                break;
            case Constants.BEGIN_SHOW_NAME:
                Log.i(TAG, "handleBeginShow");
                handleBeginShow(rsp_status, rsp_errmsg, onHandleMsgData);
                break;
            case Constants.LOGOUT_NAME:
                Log.i(TAG, "handleLogout");
                handleLogout(rsp_status, rsp_errmsg);
                break;
            default:
                Log.i(TAG, "no rsp name");
        }
    }

    /**
     * handle the returned data of get user info request
     */
    private void handleGetUserInfo(final int status, final String errmsg, final JSONObject data) {
        AppMainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status != 0) {
                    Toast.makeText(AppMainActivity.this.getApplicationContext(),
                            "ERROR: "+errmsg, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, errmsg);
                    return;
                }

                int getinfo_rsp_isbonded = 0;
                String getinfo_rsp_mobilebonded = "";
                String getinfo_rsp_nickname = "";
                int getinfo_rsp_sex = 0;

                try {
                    if (data == null) {
                        Toast.makeText(AppMainActivity.this.getApplicationContext(),
                                "获取用户信息失败", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    getinfo_rsp_isbonded = data.getInt("isbound");
                    getinfo_rsp_mobilebonded = data.getString("mobile");
                    getinfo_rsp_nickname = data.getString("nickname");
                    getinfo_rsp_sex = data.getInt("sex");
                    Log.i(TAG, String.format("getinfo_rsp_isbonded = %d", getinfo_rsp_isbonded));
                    Log.i(TAG, String.format("getinfo_rsp_mobilebonded = %s", getinfo_rsp_mobilebonded));
                    Log.i(TAG, String.format("getinfo_rsp_nickname = %s", getinfo_rsp_nickname));
                    Log.i(TAG, String.format("getinfo_rsp_sex = %d", getinfo_rsp_sex));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mBondState = getinfo_rsp_isbonded;
                mMobileBonded = getinfo_rsp_mobilebonded;
                mNickname = getinfo_rsp_nickname;
                mSex = getinfo_rsp_sex;

                //更新全局变量中的用户信息
                app.setBondState(mBondState);
                app.setPhoneNum(mMobileBonded);
                app.setNickName(mNickname);
                app.setSex(mSex);
            }
        });
    }

    /**
     * handle the returned data of begin show request
     */
    private void handleBeginShow(final int status, final String errmsg, final JSONObject data) {
        AppMainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status != 0) {
                    Toast.makeText(AppMainActivity.this.getApplicationContext(),
                            "ERROR: "+errmsg, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, errmsg);
                    return;
                }

                String beginshow_rsp_roomid;
                try {
                    if (data == null) {
                        Toast.makeText(AppMainActivity.this.getApplicationContext(), "获取roomid失败", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    beginshow_rsp_roomid = data.getString("roomid");
                    Log.i(TAG, String.format("beginshow_rsp_roomid = %s", beginshow_rsp_roomid));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                //跳转至直播间
                Intent intent = new Intent(AppMainActivity.this, MediaPublishActivity.class);
                intent.putExtra("roomName", mNickname);
                intent.putExtra("chatroomRole", Constants.USER_CHATROOM_PRESENTER);
                startActivity(intent);
            }
        });
    }

    /**
     * handle the returned data of logout request
     */
    private void handleLogout(final int status, final String errmsg) {
        AppMainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status != 0) {
                    Toast.makeText(AppMainActivity.this.getApplicationContext(),
                            "LOGOUT ERROR: "+errmsg, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, errmsg);
                    return;
                }

                Toast.makeText(AppMainActivity.this.getApplicationContext(),
                        "logout success", Toast.LENGTH_SHORT).show();
                Log.i(TAG, "logout success");
            }
        });
    }
}
